package middleware

import (
	"chatgpt/logq"
	"github.com/gin-gonic/gin"
	"github.com/slclub/go-tips"
	"github.com/slclub/go-tips/json"
	"io"
)

func RawData() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//if raw_cache, ok := ctx.Get("RawAny"); ok {
		//	if _, ok := raw_cache.(map[string]any); ok {
		//		ctx.Next()
		//		return
		//	}
		//}
		content_type := ctx.Request.Header.Get("Content-Type")
		if tips.StrPos(content_type, "multipart/form-data; boundary") != -1 {
			ctx.Next()
			return
		}
		//buf := make([]byte, 1024)
		data, _ := io.ReadAll(ctx.Request.Body)
		//n, _ := ctx.Request.Body.Read(buf)
		n := len(data)
		raw_any := make(map[string]any)
		if n >= 2 {

			err := json.Unmarshal(data, &raw_any)
			if err != nil {
				logq.Error("[REQUEST]", err)
			}
			//raw = helper.ConvMapAnyToMapString(&raw_any)
		}
		if _, ok := raw_any["Token"]; !ok {
			raw_any["Token"] = ctx.Query("Token")
		}
		ctx.Set("RawAny", raw_any)
		ctx.Next()
	}
}
